<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="divport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <title></title>
    <link href="css/mui.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="css/public.css" />
    <link rel="stylesheet" href="css/common.css" />
    <link rel="stylesheet" href="css/mailList.css" />
    <script type="text/javascript" src="js/common.js" ></script>
</head>
<body>
	<div id="hearder">
		<img src="img/goBack.png">
		<h3>客服</h3>
		<span>客服</span>
	</div>
	<div id="main">
		<div id="downPull"><span>下拉刷新</span><br/><img src="img/5-121204194026.gif"/></div>
		<div id="upPull"><span>上拉加载</span><br/><img src="img/5-121204194026.gif"/></div>
		<ul class="chatList">
			
		</ul>
	</div>
	
	<div class="discount-main-no" style="display: none;">
		<div class="discount-main-no-content">
			<img class="d-m-n-c-img" src="img/noOrder.png"></img>
			<span class="d-m-n-c-txt">暂无聊天记录</span>
		</div>
	</div>
	<div id="footer">
		<ul>
	        <li>
	            <a href="mailList.html">
	                <img src="img/msg_select.png"/><br/>
	                <span class="onspan">消息</span>
	            </a>
	        </li>
	        <li>
	            <a href="index.html">
	                <img src="img/home.png"/><br/>
	                <span>主页</span>
	            </a>
	        </li>
	        <li>
	            <a href="order.html">
	                <img src="img/order.png"/><br/>
	                <span>订单</span>
	            </a>
	        </li>
    	</ul>
	</div>
</body>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="layui/layui.js"></script>
<script src="js/commonNew.js"></script>
<script src="js/mailList.js"></script>
<script>
	var kefu=JSON.parse(storage.getItem("userinfo"));
	console.log(kefu)
	$("#main").on("click",".list",function(){
		if(kefu.user_id==null){
			taostr("此账号暂未开通客服功能！",1000);
			return;
		}
		var id=$(this).attr("_id")
		window.location.href="chat.html?id="+id;
	})
	var historyData=JSON.parse(storage.getItem("historyData"));
	console.log(historyData)
    if (historyData == null) {
        historyData = {
            'data': []    
        }
    }else{
    	for(var i=0;i<historyData.data.length;i++){
    		if(historyData.data[i].prompt==0){
    			var str3='style="display:none;"'
    		}else{
    			var str3='';
    		}
					        var str='<li class="list" _id="'+historyData.data[i].id+'">'
					        			+'<div class="clear carts-item">'
											+'<div class="float_l">'
												+'<img src="'+historyData.data[i].avatar+'"/>'
												+'<span '+str3+' class="prompt">'+historyData.data[i].prompt+'</span>'
											+'</div>'
											+'<div class="float_r">'
												+'<h4 class="clear">'
													+'<span class="titleName">'+historyData.data[i].name+'</span>'
													+'<span class="timer">'+timestampToTime(historyData.data[i].arrData[historyData.data[i].arrData.length-1].timestamp)+'</span>'
												+'</h4>'
												+'<h5>'+historyData.data[i].arrData[historyData.data[i].arrData.length-1].username+':'+historyData.data[i].arrData[historyData.data[i].arrData.length-1].content+'</h5>'
											+'</div>'
										+'</div>'
											+ '<button class="delete-button" list_id="' + historyData.data[i].id + '" onclick="deleteList(this)">删除</button>'
										+'</li>'
				       $(".chatList").prepend(str)
				    }
    }
    layui.use('layim', function(layim){
        //基础配置
        layim.config({

            //获取主面板列表信息
            init: {
                url: "{:url('index/getList')}" //接口地址（返回的数据格式见下文）
                ,type: 'get' //默认get，一般可不填
                ,data: {} //额外参数
            }
            //获取群员接口
            ,members: {
                url: "{:url('index/getMembers')}" //接口地址（返回的数据格式见下文）
                ,type: 'get' //默认get，一般可不填
                ,data: {} //额外参数
            }
            ,brief: true //是否简约模式（默认false，如果只用到在线客服，且不想显示主面板，可以设置 true）
            ,title: '我的LayIM' //主面板最小化后显示的名称
            ,maxLength: 3000 //最长发送的字符长度，默认3000
            ,isfriend: true //是否开启好友（默认true，即开启）
            ,isgroup: true //是否开启群组（默认true，即开启）
            ,right: '0px' //默认0px，用于设定主面板右偏移量。该参数可避免遮盖你页面右下角已经的bar。
            ,chatLog: "{:url('Chatlog/index')}" //聊天记录地址（如果未填则不显示）
            ,find: "{:url('findgroup/index')}" //查找好友/群的地址（如果未填则不显示）
            ,copyright: false //是否授权，如果通过官网捐赠获得LayIM，此处可填true
        });

        //建立WebSocket通讯
        //var local='192.168.1.109';
        var local='47.94.17.241';
        var socket = new WebSocket('ws://'+local+':7272');
        //连接成功时触发
        socket.onopen = function(){
            // 登录
            var login_data = '{"type":"init","id":"'+kefu.user_id+'","username":"'+kefu.nickname+'","avatar":"'+kefu.pimg_url+'","sign":""}';
            socket.send( login_data );
            console.log( login_data );
            console.log("websocket握手成功!");
        };
        

        //监听收到的消息
        socket.onmessage = function(res){
            //console.log(res.data);
            var data = eval("("+res.data+")");
            switch(data['message_type']){
                // 服务端ping客户端
                case 'ping':
                    socket.send('{"type":"ping"}');
                    break;
                // 登录 更新用户列表
                case 'init':
                    console.log(res.data);
                    //console.log(data['id']+"登录成功");
                    //layim.getMessage(res.data); //res.data即你发送消息传递的数据（阅读：监听发送的消息）
                    break;
                // 检测聊天数据
                case 'chatMessage':
                console.log(data.data)
                for(var i=0;i<historyData.data.length;i++){
	                if(historyData.data[i].id==data.data.id){
	                	historyData.data[i].arrData.push(data.data);
	                	historyData.data[i].prompt=parseInt(historyData.data[i].prompt)+1
	                	console.log(historyData)
	                	storage.setItem("historyData",JSON.stringify(historyData));	   
	                	var list=$(".list");
	                	for(var j=0;j<list.length;j++){
	                		if(list.eq(j).attr("_id")==data.data.id){
	                			list.eq(j).find(".prompt").text(historyData.data[i].prompt).css("display","block")
	                			list.eq(j).find("h5").text(historyData.data[i].arrData[historyData.data[i].arrData.length-1].username+':'+historyData.data[i].arrData[historyData.data[i].arrData.length-1].content)
	                			list.eq(j).find(".timer").text(timestampToTime(historyData.data[i].arrData[historyData.data[i].arrData.length-1].timestamp))
	                		}
	                	}
	                	return;
	                }
                }
                var str='<li class="list" _id="'+data.data.id+'">'
                			+'<div class="clear carts-item">'
								+'<div class="float_l">'
									+'<img src="'+data.data.avatar+'"/>'
									+'<span class="prompt">1</span>'
								+'</div>'
								+'<div class="float_r">'
									+'<h4 class="clear">'
										+'<span class="titleName">'+data.data.username+'</span>'
										+'<span class="timer">'+timestampToTime(data.data.timestamp)+'</span>'
									+'</h4>'
									+'<h5>'+data.data.username+':'+data.data.content+'</h5>'
								+'</div>'
							+'</div>'
							+ '<button class="delete-button" list_id="' + data.data.id + '" onclick="deleteList(this)">删除</button>'
						+'</li>'
       			$(".chatList").prepend(str)
                historyData.data.push({'id':data.data.id,'avatar':data.data.avatar,'prompt':1,'name':data.data.username,'arrData':[data.data]})               
                storage.setItem("historyData",JSON.stringify(historyData));
	          
                    var listObj=$(".list")
				    if(listObj.length==0){
				    	$(".discount-main-no").show()
				    }else{
				    	$(".discount-main-no").hide()
				    }
                    break;
                // 离线消息推送
                case 'logMessage':
                for(var i=0;i<historyData.data.length;i++){
	                if(historyData.data[i].id==data.data.id){
	                	historyData.data[i].arrData.push(data.data);
	                	historyData.data[i].prompt=parseInt(historyData.data[i].prompt)+1
	                	console.log(historyData)
	                	storage.setItem("historyData",JSON.stringify(historyData));	                	
	                	var list=$(".list");
	                	for(var j=0;j<list.length;j++){
	                		if(list.eq(j).attr("_id")==data.data.id){
	                			list.eq(j).find(".prompt").text(historyData.data[i].prompt).css("display","block")
	                			list.eq(j).find("h5").text(historyData.data[i].arrData[historyData.data[i].arrData.length-1].username+':'+historyData.data[i].arrData[historyData.data[i].arrData.length-1].content)
	                			list.eq(j).find(".timer").text(timestampToTime(historyData.data[i].arrData[historyData.data[i].arrData.length-1].timestamp))
	                		}
	                	}
	                	return;
	                }
                }                      
                var str='<li class="list" _id="'+data.data.id+'">'
                +'<div class="clear carts-item">'
							+'<div class="float_l">'
								+'<img src="'+data.data.avatar+'"/>'
								+'<span class="prompt">1</span>'
							+'</div>'
							+'<div class="float_r">'
								+'<h4 class="clear">'
									+'<span class="titleName">'+data.data.username+'</span>'
									+'<span class="timer">'+timestampToTime(data.data.timestamp)+'</span>'
								+'</h4>'
								+'<h5>'+data.data.username+':'+data.data.content+'</h5>'
							+'</div>'
							+ '<button class="delete-button" list_id="' + data.data.id + '" onclick="deleteList(this)">删除</button>'
						+'</li>'
       			$(".chatList").prepend(str)
                historyData.data.push({'id':data.data.id,'prompt':1,'avatar':data.data.avatar,'name':data.data.username,'arrData':[data.data]})               
                storage.setItem("historyData",JSON.stringify(historyData));	                                                       
                    //setTimeout(function(){layim.getMessage(data.data)}, 1000);
                    var listObj=$(".list")
				    if(listObj.length==0){
				    	$(".discount-main-no").show()
				    }else{
				    	$(".discount-main-no").hide()
				    }
                    break;
                // 用户退出 更新用户列表
                case 'logout':
                    break;
                //聊天还有不在线
                case 'ctUserOutline':
                    //console.log('11111');
                    //layer.msg('好友不在线', {'time' : 1000});
                    break;
            }
        };
    });
    var listObj=$(".list")
    if(listObj.length==0){
    	$(".discount-main-no").show()
    }else{
    	$(".discount-main-no").hide()
    }
</script>
</html>